package com.yihr;

import jdk.management.resource.internal.inst.InitInstrumentation;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.file.nativefs.NativeFileSystemFactory;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.CommandFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.config.keys.DefaultAuthorizedKeysAuthenticator;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.shell.ProcessShellFactory;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yihr-pc on 2017/9/29.
 */
public class Main {

    static public Logger logger = LoggerFactory.getLogger(Main.class);

    public void serverTest() throws IOException, InterruptedException
    {
        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(6666);

        //*give host key generator a path, when sshd server restart, the same key will be load and used to authenticate the server
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        sshd.setPasswordAuthenticator(new PasswordAuthenticator(){
            @Override
            public boolean authenticate(String username, String password, ServerSession session) {
                System.out.println("authen:  user="+username+"  password="+password);
                if("123123".equals(username) && "123456".equals(password))
                    return true;
                return false;
            }});

        logger.error("sa  12323");

        //use file ~/.ssh/authorized_keys
        sshd.setPublickeyAuthenticator(new DefaultAuthorizedKeysAuthenticator(false));

        SftpSubsystemFactory sftpSubsystemFactory= new SftpSubsystemFactory();

        List<NamedFactory<Command>> subsystemFactories = new ArrayList<NamedFactory<Command>>(1);
        subsystemFactories.add(new SftpSubsystemFactory());
        sshd.setSubsystemFactories(subsystemFactories);


        File file = new File("I:\\desk");
        System.out.println(file.getAbsoluteFile().toString());
        System.out.println(file.isDirectory() + "");
        sshd.setFileSystemFactory(new VirtualFileSystemFactory(file.toPath()));

        //* CommandFactory can be userd in addition to the ShellFactory,
        //*  it can also be used instead of the ShellFactory.
        //*  The CommandFactory is used when direct commands are sent to the SSH server,
        //*  as this is the case when running ssh localhost shutdown or scp xxx
        ScpCommandFactory scpCmdFactory=new ScpCommandFactory();
        scpCmdFactory.setDelegateCommandFactory(new CommandFactory() {
            public Command createCommand(String command) {
                System.out.println("command = \"" + command + "\"");
                return new ProcessShellFactory(("cmd /c "+command).split(" ")).create();
            }
        });
        sshd.setCommandFactory(scpCmdFactory);

        sshd.start();
    }

    public static void main(String[] args) throws IOException, InterruptedException {
//        SimpleSshServer.embedding();

        new Main().serverTest();

        // 记录debug级别的信息
        logger.debug("This is debug message.");
        // 记录info级别的信息
        logger.info("This is info message.");
        // 记录error级别的信息
        logger.error("This is error message.");


        boolean isKeepAlive = true;
        while (isKeepAlive) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {

                logger.error("Exception occurred " + e);
            }
        }
    }

    public static void main00(String[] args) {

        SshServer sshd = SshServer.setUpDefaultServer();

        sshd.setPort(6666);

//        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));

        sshd.setPasswordAuthenticator(new PasswordAuthenticator(){
            @Override
            public boolean authenticate(String username, String password, ServerSession session) {
                System.out.println("authen:  user="+username+"  password="+password);
                if("123456".equals(username) && "123456".equals(password))
                    return true;
                return false;
            }});


        //* CommandFactory can be userd in addition to the ShellFactory,
        //*  it can also be used instead of the ShellFactory.
        //*  The CommandFactory is used when direct commands are sent to the SSH server,
        //*  as this is the case when running ssh localhost shutdown or scp xxx
        ScpCommandFactory scpCmdFactory=new ScpCommandFactory();
        scpCmdFactory.setDelegateCommandFactory(new CommandFactory() {
            public Command createCommand(String command) {
                System.out.println("command = \"" + command + "\"");
                return new ProcessShellFactory(("cmd /c "+command).split(" ")).create();
            }
        });
        sshd.setCommandFactory(scpCmdFactory);


//        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(
//                new File("hostkey.ser")));

        //*give host key generator a path, when sshd server restart, the same key will be load and used to authenticate the server
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i", "-l" }));

//        sshd.setCommandFactory(new ScpCommandFactory());


        sshd.setFileSystemFactory(new NativeFileSystemFactory());

        try {
            sshd.start();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }

    }
}
